<template>
  <div class="app-container">
    <!-- 树形结构菜单 -->
    <splitpanes
      :horizontal="this.$store.getters.device === 'mobile'"
      class="default-theme"
      style="height: 100vh"
    >
      <pane size="10">
        <div class="head-container">
          <el-input
            v-model="projectName"
            placeholder="请输入培训项目"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin-bottom: 20px; width: 70%"
          />
        </div>
        <div class="head-container">
          <el-tree
            :data="projectOptions"
            :props="defaultProps"
            :expand-on-click-node="false"
            :filter-node-method="filterNode"
            ref="tree"
            node-key="id"
            default-expand-all
            highlight-current
            @node-click="handleNodeClick"
          />
        </div>
      </pane>
    </splitpanes>
    <el-col :span="20">
      <!-- 搜索栏 -->
      <el-form
        :model="queryParams"
        ref="queryForm"
        size="small"
        v-show="showSearch"
        label-width="80px"
      >
        <el-row :gutter="20">
          <!-- 第一行 -->
          <el-col :span="6">
            <el-form-item label="姓名" prop="studentName">
              <el-input
                v-model="queryParams.studentName"
                placeholder="请输入姓名"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="缴费状态" prop="paymentState">
              <el-select
                v-model="queryParams.paymentState"
                placeholder="请选择缴费状态"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.payment_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="缴费方式" prop="paymentMethod">
              <el-select
                v-model="queryParams.paymentMethod"
                placeholder="请选择缴费方式"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.payment_method"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="缴费时间" prop="paymentTimeRange">
              <el-date-picker
                v-model="queryParams.paymentTimeRange"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="诺诺单号" prop="nuonuoNumber">
              <el-input
                v-model="queryParams.nuonuoNumber"
                placeholder="请输入诺诺单号"
                clearable
                @keyup.enter.native="handleQuery"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="证件编号" prop="idNumber">
              <el-input
                v-model="queryParams.idNumber"
                placeholder="请输入证件编号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="单位名称" prop="unitName">
              <el-input
                v-model="queryParams.unitName"
                placeholder="请输入单位名称"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input
                v-model="queryParams.phonenumber"
                placeholder="请输入手机号码"
                clearable
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="费用金额" prop="paymentAmount">
              <el-input
                v-model="queryParams.paymentAmount"
                placeholder="请输入费用金额"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="培训类型" prop="trainingType">
              <el-select
                v-model="queryParams.trainingType"
                placeholder="请选择培训类型"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.training_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="办结情况" prop="isSettled">
              <el-select
                v-model="queryParams.isSettled"
                placeholder="请选择办结情况"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.is_settled"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="开票时间" prop="invoiceTimeRange">
              <el-date-picker
                v-model="queryParams.invoiceTimeRange"
                type="daterange"
                range-separator="-"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                value-format="yyyy-MM-dd"
                clearable
                style="width: 100%"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行 -->
        <el-row :gutter="20">
          <el-col :span="6">
            <el-form-item label="备注" prop="remark">
              <el-input
                v-model="queryParams.remark"
                placeholder="请输入备注内容"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发票状态" prop="invoiceStatus">
              <el-select
                v-model="queryParams.invoiceStatus"
                placeholder="请选择发票状态"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.invoice_status"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="发票类型" prop="invoiceType">
              <el-select
                v-model="queryParams.invoiceType"
                placeholder="请选择发票类型"
                clearable
              >
                <el-option
                  v-for="dict in dict.type.invoice_type"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <!-- 操作按钮 -->
            <el-form-item>
              <el-button
                type="primary"
                icon="el-icon-search"
                size="mini"
                @click="handleQuery"
                >搜索</el-button
              >
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
                >重置</el-button
              >
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 操作按钮栏 -->
      <el-row :gutter="20" class="mb8">
        <!-- 分组：缴费列表 -->
        <el-col :span="12"
          ><el-button-group>
            <el-button type="primary">缴费列表</el-button>
            <el-button
              type="primary"
              plain
              @click="handleExport"
              v-hasPermi="['training:record:export']"
              >导出</el-button
            >
            <el-button type="primary" plain @click="handleRemark"
              >缴费备注</el-button
            >
          </el-button-group></el-col
        >
        <!-- 刷新 -->
        <el-col :span="12">
          <el-button-group class="button-group-right">
            <el-button type="primary" plain @click="toggleSearch"
              >隐藏搜索</el-button
            >
            <el-button type="primary" plain @click="refreshTable"
              >刷新</el-button
            >
            <el-button type="primary" plain @click="toggleSort"
              >隐藏/排序列</el-button
            >
          </el-button-group>
        </el-col>
        <!-- 分组：缴费信息 -->
        <el-col :span="12" style="margin-top: 10px">
          <el-button-group>
            <el-button type="primary">缴费信息</el-button>

            <el-button
              type="primary"
              plain
              @click="handleViewDetail"
              :disabled="single"
              >查看缴费明细</el-button
            >
            <el-button
              type="primary"
              plain
              @click="handleEditDetail"
              :disabled="single"
              >修改缴费明细</el-button
            >
          </el-button-group>
        </el-col>
        <!-- 开票 -->
        <el-col :span="12" style="margin-top: 10px">
          <el-button-group>
            <el-button type="primary">开票</el-button>
            <el-button
              type="primary"
              plain
              @click="handleEditInvoiceInfo()"
              :disabled="single"
              >编辑开票信息</el-button
            >
            <el-button type="primary" plain @click="handleIssueInvoice"
              >开发票</el-button
            >
            <el-button
              type="primary"
              plain
              @click="handleMergeInvoice"
              :disabled="multiple"
              >合并开票</el-button
            >
            <el-button type="primary" plain @click="handleViewInvoice"
              >查看发票</el-button
            >
          </el-button-group>
        </el-col>
        <!-- 分组：更改缴费方式 -->
        <el-col :span="12" style="margin-top: 10px"
          ><el-button-group>
            <el-button type="primary">更改缴费方式</el-button>
            <el-button
              type="primary"
              plain
              @click="handlePayOnline"
              :disabled="single"
              >线上缴费</el-button
            >
            <el-button
              type="primary"
              plain
              @click="handleTransferPay"
              :disabled="single"
              >转账缴费</el-button
            >
            <el-button
              type="primary"
              plain
              @click="handleCashPay"
              :disabled="single"
              >现金缴费</el-button
            >
            <el-button
              type="primary"
              plain
              @click="handlePosPay"
              :disabled="single"
              >POS机缴费</el-button
            >
          </el-button-group></el-col
        >
        <!-- 退换票 -->
        <el-col :span="12" style="margin-top: 10px">
          <el-button-group>
            <el-button type="primary">退换票</el-button>
            <el-button type="primary" plain @click="handleApplyExchange()"
              >申请退换票</el-button
            >
            <el-button type="primary" plain @click="handleAgreeExchange"
              >同意退换票</el-button
            >
            <el-button type="primary" plain @click="handleStartExchange"
              >发起退换票</el-button
            >
            <el-button type="primary" plain @click="handleCancelExchange"
              >取消退换票</el-button
            >
          </el-button-group>
        </el-col>
        <!-- 分组：转账情况 -->
        <el-col :span="24" style="margin-top: 10px">
          <el-button-group>
            <el-button type="primary">转账情况</el-button>
            <el-button type="primary" plain @click="handleViewTransfer"
              >查看转账凭证</el-button
            >
            <el-button
              type="primary"
              plain
              @click="handlePendingTransfer"
              :disabled="single"
              >待转账</el-button
            >
            <el-button
              type="primary"
              plain
              @click="handleTransfered"
              :disabled="single"
              >已转账</el-button
            >
            <el-button
              type="primary"
              plain
              @click="handleCashTransfered"
              :disabled="single"
              >已现金缴费</el-button
            >
            <el-button
              type="primary"
              plain
              @click="handlePosTransfered"
              :disabled="single"
              >已POS缴费</el-button
            >
          </el-button-group></el-col
        >
        <!-- 分组：退费 -->
        <el-col :span="24" style="margin-top: 10px">
          <el-button-group>
            <el-button type="primary">退费</el-button>
            <el-button type="primary" plain @click="handleApplyRefund"
              >查看退费申请</el-button
            >
            <el-button type="primary" plain @click="handleAgreeRefund"
              >同意退费</el-button
            >
            <el-button type="primary" plain @click="handleCancelAgreeRefund"
              >取消同意退费</el-button
            >
            <el-button type="primary" plain @click="handleStartRefund"
              >发起退费</el-button
            >
            <el-button type="primary" plain @click="handleCancelRefund"
              >取消退费</el-button
            >
            <el-button type="primary" plain @click="handleAuditRefund"
              >审核退费</el-button
            >
          </el-button-group></el-col
        >
      </el-row>

      <!-- 对应组件 -->
      <PaymentRemarks
        :visible="showRemark && remarkTempId !== null"
        :title="`缴费备注`"
        :business-id="remarkTempId || ''"
        :initial-remark="defaultRemark"
        :remarkTempId="remarkTempId"
        :max-length="300"
        @submit="handleRemarkSubmit"
        @close="handleRemarkClose"
      ></PaymentRemarks>
      <FeeViewDialog
        :visible.sync="showDialogCheck"
        :form-data="formDataCheck"
        :dict="dictCache"
        :query-params-data="queryParams"
        @cancel="handleFormCancel"
      ></FeeViewDialog>
      <FeeUpdateDialog
        :visible.sync="showDialogUpdate"
        :form-data="formData"
        :dict="dictCache"
        :query-params-data="queryParams"
        @confirm="handleFormConfirm"
        @cancel="handleFormCancel"
      ></FeeUpdateDialog>
      <ViewTransferVoucherDialog
        :visible.sync="showDialogVoucher"
        :voucher-data="voucherInfo"
        :dict="dictCache"
        @confirm-transferred="handleConfirmTransferred"
        @close="handleVoucherDialogClose"
      ></ViewTransferVoucherDialog>
      <CheckRefundApplication
        :visible.sync="showRefundDialog"
        :apply-info="refundApplyInfo"
        :dict="dictCache"
        @submit="handleRefundSubmit"
        @close="handleCheckRefundClose"
      ></CheckRefundApplication>
      <InitiateRefundDialog
        :visible.sync="showRefundDialogInitiate"
        :apply-info="refundFormData"
        :dict="dictCache"
        @submit="handleRefundSubmitInitiate"
        @close="handleInitiateRefundClose"
      ></InitiateRefundDialog>
      <CancelRefundDialog
        :visible.sync="showRefundDialogCancel"
        :apply-info="refundApplyInfoCancel"
        :dict="dictCache"
        @submit="handleRefundSubmitCancel"
      ></CancelRefundDialog>
      <EditInvoiceInfoDialog
        :visible="showEditInvoiceInfo"
        :dict="dictCache"
        :formData="invoiceFormData"
        @submit="handleInvoiceSubmit"
        @close="handleEditInvoiceClose"
      ></EditInvoiceInfoDialog>
      <IssueInvoiceDialog
        :visible="showIssueInvoice"
        :count="selectedCount"
        @confirm="handleInvoiceConfirm"
        @close="handleIssueInvoiceClose"
      ></IssueInvoiceDialog>
      <MergeInvoiceDialog
        :visible="showMergeInvoice"
        :formData="mergeInvoiceFormData"
        @submit="handleMergeInvoiceSubmit"
        @close="handleMergeInvoiceClose"
      ></MergeInvoiceDialog>
      <ExchangeApplicationDialog
        :visible.sync="showExchangeDialog"
        :form-data="applyExchangeFormData"
        :dict="dictCache"
        @submit="handleExchangeSubmit"
        @close="handleExchangeClose"
      ></ExchangeApplicationDialog>
      <StartExchangeDialog
        :visible.sync="showStartExchangeDialog"
        :formData="startExchangeFormData"
        :dict="dictCache"
        @submit="handleExchangeSubmit"
        @close="handleStartExchangeClose"
      />
      <CancelExchangeDialog
        :visible.sync="showCancelExchangeDialog"
        :formData="cancelExchangeFormData"
        :dict="dictCache"
        @submit="handleCancelExchangeSubmit"
        @close="handleCancelExchangeClose"
      />

      <!-- 数据表格 -->
      <el-table
        v-loading="loading"
        :data="recordList"
        @selection-change="handleSelectionChange"
      >
        <!-- 选择框 -->
        <el-table-column type="selection" width="55" align="center" />

        <!-- 是否办结 -->
        <el-table-column label="是否办结" align="center" prop="isSettled">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.is_settled"
              :value="scope.row.isSettled"
            />
          </template>
        </el-table-column>

        <!-- 缴费状态 -->
        <el-table-column label="缴费状态" align="center" prop="paymentState">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.payment_status"
              :value="scope.row.paymentState"
            />
          </template>
        </el-table-column>

        <!-- 发票状态 -->
        <el-table-column label="发票状态" align="center" prop="invoiceStatus">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.invoice_status"
              :value="scope.row.invoiceStatus"
            />
          </template>
        </el-table-column>

        <!-- 缴费方式 -->
        <el-table-column label="缴费方式" align="center" prop="paymentMethod">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.payment_method"
              :value="scope.row.paymentMethod"
            />
          </template>
        </el-table-column>

        <!-- 诺诺单号 -->
        <el-table-column label="诺诺单号" align="center" prop="nuonuoNumber" />

        <!-- 发票种类 -->
        <el-table-column label="发票种类" align="center" prop="invoiceCategory">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.invoice_category"
              :value="scope.row.invoiceCategory"
            />
          </template>
        </el-table-column>

        <!-- 发票类型 -->
        <el-table-column label="发票类型" align="center" prop="invoiceType">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.invoice_type"
              :value="scope.row.invoiceType"
            />
          </template>
        </el-table-column>

        <!-- 姓名 -->
        <el-table-column label="姓名" align="center" prop="studentName" />

        <!-- 证件编号 -->
        <el-table-column label="证件编号" align="center" prop="idNumber" />

        <!-- 电话 -->
        <el-table-column label="电话" align="center" prop="phonenumber" />

        <!-- 单位名称 -->
        <el-table-column label="单位名称" align="center" prop="unitName" />

        <!-- 单位统一信用代码 -->
        <el-table-column
          label="单位统一信用代码"
          align="center"
          prop="invoiceCreditCode"
        />

        <!-- 报名来源 -->
        <el-table-column
          label="报名来源"
          align="center"
          prop="registrationMethod"
        >
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.registration_method"
              :value="scope.row.registrationMethod"
            />
          </template>
        </el-table-column>

        <!-- 联系人 -->
        <el-table-column label="联系人" align="center" prop="contact" />

        <!-- 联系人电话 -->
        <el-table-column
          label="联系人电话"
          align="center"
          prop="unitPhonenumber"
        />

        <!-- 培训类型 -->
        <el-table-column label="培训类型" align="center" prop="trainingType">
          <template slot-scope="scope">
            <dict-tag
              :options="dict.type.training_type"
              :value="scope.row.trainingType"
            />
          </template>
        </el-table-column>
        <!-- 培训项目 -->
        <el-table-column label="培训项目" align="center" prop="projectMap" />

        <!-- 教学班 -->
        <el-table-column label="教学班" align="center" prop="trainingClass" />

        <!-- 培训费 -->
        <!-- <el-table-column label="费用" align="center" prop="projectSum" /> -->
        <el-table-column label="费用" align="center" prop="paymentAmount" />

        <!-- 退费 -->
        <el-table-column label="退费" align="center" prop="refundAmount" />

        <!-- 缴费时间 -->
        <el-table-column
          label="缴费时间"
          align="center"
          prop="paymentTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.paymentTime, "{y}-{m}-{d} {h}:{i}")
            }}</span>
          </template>
        </el-table-column>

        <!-- 上传缴费凭证时间 -->
        <el-table-column
          label="上传缴费凭证时间"
          align="center"
          prop="voucherUploadTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.voucherUploadTime, "{y}-{m}-{d} {h}:{i}")
            }}</span>
          </template>
        </el-table-column>

        <!-- 报名时间 -->
        <el-table-column
          label="报名时间"
          align="center"
          prop="enrollmentTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{
              parseTime(scope.row.enrollmentTime, "{y}-{m}-{d} {h}:{i}")
            }}</span>
          </template>
        </el-table-column>

        <!-- 备注 -->
        <el-table-column label="备注" align="center" prop="remark" />

        <!-- 操作列 -->
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="200px"
          fixed="right"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleViewDetail(scope.row)"
              >查看</el-button
            >
            <el-button size="mini" type="text" @click="handlePay(scope.row)"
              >已缴费</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleApplyRefund(scope.row)"
              >退费</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleIssueInvoice(scope.row)"
              >开票</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleApplyExchange(scope.row)"
              >退换票</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleEditInvoiceInfo(scope.row)"
              >开票信息</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="handleDelete(scope.row)"
              v-hasPermi="['training:record:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />

      <!-- 添加或修改缴费记录对话框 -->
      <el-dialog
        :title="title"
        :visible.sync="open"
        width="500px"
        append-to-body
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-form-item label="缴费状态" prop="paymentState">
            <el-select v-model="form.paymentState" placeholder="请选择缴费状态">
              <el-option
                v-for="dict in dict.type.payment_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="缴费方式" prop="paymentMethod">
            <el-select
              v-model="form.paymentMethod"
              placeholder="请选择缴费方式"
            >
              <el-option
                v-for="dict in dict.type.payment_method"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="费用" prop="paymentAmount">
            <el-input v-model="form.paymentAmount" placeholder="请输入费用" />
          </el-form-item>
          <el-form-item label="诺诺单号" prop="nuonuoNumber">
            <el-input
              v-model="form.nuonuoNumber"
              placeholder="请输入诺诺单号"
            />
          </el-form-item>
          <el-form-item label="缴费凭证" prop="paymentVoucher">
            <el-input
              v-model="form.paymentVoucher"
              placeholder="请输入缴费凭证"
            />
          </el-form-item>
          <el-form-item label="退费金额" prop="refundAmount">
            <el-input
              v-model="form.refundAmount"
              placeholder="请输入退费金额"
            />
          </el-form-item>
          <el-form-item label="退费原因" prop="refundReason">
            <el-input
              v-model="form.refundReason"
              placeholder="请输入退费原因"
            />
          </el-form-item>
          <el-form-item label="是否办结" prop="isSettled">
            <el-select v-model="form.isSettled" placeholder="请选择是否办结">
              <el-option
                v-for="dict in dict.type.is_settled"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="上传缴费凭证时间" prop="voucherUploadTime">
            <el-date-picker
              clearable
              v-model="form.voucherUploadTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择上传缴费凭证时间"
            >
            </el-date-picker>
          </el-form-item>
          <el-form-item label="缴费时间" prop="paymentTime">
            <el-date-picker
              clearable
              v-model="form.paymentTime"
              type="date"
              value-format="yyyy-MM-dd"
              placeholder="请选择缴费时间"
            >
            </el-date-picker>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </el-dialog>
    </el-col>

    <!-- 同意退换票确认弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="agreeExchangeDialogVisible"
      width="400px"
      center
    >
      <div style="text-align: center; padding: 20px">
        <p>是否同意“{{ exchangeRefundName }}”的退费申请？</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="agreeExchangeDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAgreeRefund">确定</el-button>
      </div>
    </el-dialog>

    <!-- 同意退费确认弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="agreeRefundDialogVisible"
      width="400px"
      center
    >
      <div style="text-align: center; padding: 20px">
        <p>是否同意“{{ refundName }}”的退费申请？</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="agreeRefundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleAgreeRefundSubmit"
          >确定</el-button
        >
      </div>
    </el-dialog>

    <!-- 审核退费确认弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="auditRefundDialogVisible"
      width="400px"
      center
    >
      <div style="text-align: center; padding: 20px">
        <p>是否审核通过“{{ auditRefundNames.join("、") }}”的退费？</p>
        <p style="color: #f56c6c; font-size: 12px; margin-top: 8px">
          注：通过后将不可再撤回
        </p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="auditRefundDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmAuditRefund">确定</el-button>
      </div>
    </el-dialog>

    <!-- 取消同意退费确认弹窗 -->
    <el-dialog
      :title="dialogTitle"
      :visible.sync="cancelAgreeRefundDialogVisible"
      width="400px"
      center
    >
      <div style="text-align: center; padding: 20px">
        <p>是否取消同意“{{ refundName }}”的退费申请？</p>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="cancelAgreeRefundDialogVisible = false"
          >取消</el-button
        >
        <el-button type="primary" @click="confirmCancelAgreeRefund"
          >确定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listRecord,
  getRecord,
  delRecord,
  addRecord,
  updateRecord,
  paymentRecordList,
  getPayInfo,
  changePay,
  getRefundInfo,
} from "@/api/payment/payment";
import { Splitpanes, Pane } from "splitpanes";
import "splitpanes/dist/splitpanes.css";
import { projectTreeSelect } from "@/api/training/projects";
// 缴费备注
import PaymentRemarks from "@/components/Payment/PaymentRemarksDialog.vue";
// 查看缴费明细
import FeeViewDialog from "@/components/Payment/FeeViewDialog.vue";
// 修改缴费明细
import FeeUpdateDialog from "@/components/Payment/FeeUpdateDialog.vue";
// 查看退费申请
import CheckRefundApplication from "@/components/Payment/CheckRefundApplicationDialog.vue";
// 发起退费
import InitiateRefundDialog from "@/components/Payment/InitiateRefundDialog.vue";
// 取消退费
import CancelRefundDialog from "@/components/Payment/CancelRefundDialog.vue";
// 转账凭证
import ViewTransferVoucherDialog from "@/components/Payment/ViewTransferVoucherDialog.vue";
// 编辑开票信息
import EditInvoiceInfoDialog from "@/components/Payment/EditInvoiceInfoDialog.vue";
// 开发票
import IssueInvoiceDialog from "@/components/Payment/IssueInvoiceDialog.vue";
// 新增：合并开票对话框
import MergeInvoiceDialog from "@/components/Payment/MergeInvoiceDialog.vue";
// 申请退换票
import ExchangeApplicationDialog from "@/components/Payment/ExchangeApplicationDialog.vue";
// 发起退换票
import StartExchangeDialog from "@/components/Payment/StartExchangeDialog.vue";
// 取消退换票
import CancelExchangeDialog from "@/components/Payment/CancelExchangeDialog.vue";

import { getRemarksByParams, addRemarks } from "@/api/training/remarks";
import { updateInvoice, getInvoiceRefundInfo } from "@/api/payment/invoice";
import { getDicts } from "@/api/system/dict/data";

export default {
  name: "Record",
  dicts: [
    "payment_method",
    "is_settled",
    "payment_status",
    "invoice_status",
    "invoice_type",
    "invoice_category",
    "administrative_area",
    "unit_nature",
    "registration_method",
    "training_type",
  ],
  components: {
    Splitpanes,
    Pane,
    PaymentRemarks,
    FeeViewDialog,
    FeeUpdateDialog,
    ViewTransferVoucherDialog,
    CheckRefundApplication,
    InitiateRefundDialog,
    CancelRefundDialog,
    EditInvoiceInfoDialog,
    IssueInvoiceDialog,
    MergeInvoiceDialog,
    ExchangeApplicationDialog,
    StartExchangeDialog,
    CancelExchangeDialog,
  },
  data() {
    return {
      //解决报错新增定义首

      cancelExchangeFormData: {},
      //解决报错新增定义尾
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 缴费记录表格数据
      recordList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        paymentState: null,
        paymentMethod: null,
        nuonuoNumber: null,
        isSettled: null,
        paymentTime: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},

      //新增定义
      // 所有部门树选项
      projectOptions: null,
      //树形结构数据
      projectName: "",
      defaultProps: {
        children: "children",
        label: "label",
      },
      //缴费备注
      showRemark: false,
      //编辑缴费明细
      showDialogUpdate: false,
      //查看缴费明细
      showDialogCheck: false,
      //查看转账凭证
      showDialogVoucher: false,
      voucherInfo: {},
      // 退费申请
      showRefundDialog: false,
      refundApplyInfo: {},
      // 退费发起
      showRefundDialogInitiate: false,
      refundFormData: {},
      // 退费取消
      showRefundDialogCancel: false,
      refundApplyInfoCancel: {},
      // 编辑开票信息
      showEditInvoiceInfo: false,
      invoiceFormData: {
        invoiceType: "",
        invoiceCategory: "",
        invoiceUnitName: "",
        invoiceCreditCode: "",
      },
      // 开发票
      showIssueInvoice: false,
      selectedCount: 0,
      // 合并开票
      showMergeInvoice: false,
      mergeInvoiceFormData: {
        unitName: "",
        invoiceCreditCode: "",
        invoicePhone: "",
      },
      // 退换票申请
      showExchangeDialog: false,
      applyExchangeFormData: {},
      // 同意退换票
      // 控制弹窗显示与隐藏，以及记录申请人姓名
      agreeExchangeDialogVisible: false,
      exchangeRefundName: "",
      dialogTitle: "系统提示",
      // 发起退换票
      showStartExchangeDialog: false,
      startExchangeFormData: {}, // 存储选中的记录数据
      // 取消退换票
      showCancelExchangeDialog: false,
      cancelExchangeFormData: {}, // 存储选中的记录数据
      // 同意退费
      agreeRefundDialogVisible: false,
      refundName: "", // “同意退费”的申请人姓名
      // 审核退费
      auditRefundDialogVisible: false,
      auditRefundNames: [], // 存储多个申请人姓名（支持多选）
      //备注弹窗
      remarkTempId: "", //备注弹窗  参数ID
      defaultRemark: "", //传给组件的备注内容
      currentPaymentId: null, //传给组件的参数ID
      //查看缴费明细数据
      formDataCheck: {},
      //编辑缴费明细数据
      formData: {},
      //取消同意退费申请
      cancelAgreeRefundDialogVisible: false, // 控制弹窗显示隐藏
      refundName: "", // 存储申请人姓名
      dialogTitle: "系统提示",
      // 缓存字典数据
      dictCache: {
        payment_method: {},
        is_settled: {},
        payment_status: {},
        invoice_status: {},
        invoice_type: {},
        invoice_category: {},
        administrative_area: {},
        unit_nature: {},
        registration_method: {},
        training_type: {},
      },
    };
  },
  async created() {
    this.getList();
    this.getProjectTree();
    this.$nextTick(async () => {
      await this.loadDicts();
    });
  },
  methods: {
    async loadDicts() {
      this.dictCache.payment_method = this.dict.label.payment_method;
      this.dictCache.is_settled = this.dict.label.is_settled;
      this.dictCache.payment_status = this.dict.label.payment_status;
      this.dictCache.invoice_status = this.dict.label.invoice_status;
      this.dictCache.invoice_type = this.dict.label.invoice_type;
      this.dictCache.invoice_category = this.dict.label.invoice_category;
      this.dictCache.administrative_area = this.dict.label.administrative_area;
      this.dictCache.unit_nature = this.dict.label.unit_nature;
      this.dictCache.registration_method = this.dict.label.registration_method;
      this.dictCache.training_type = this.dict.label.training_type;
    },
    /** 查询缴费记录列表 */
    getList() {
      this.loading = true;
      paymentRecordList(this.queryParams).then((response) => {
        this.recordList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        paymentRecordId: null,
        paymentState: null,
        paymentMethod: null,
        paymentAmount: null,
        nuonuoNumber: null,
        paymentVoucher: null,
        refundAmount: null,
        refundReason: null,
        isSettled: null,
        voucherUploadTime: null,
        paymentTime: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        exampleOne: null,
        exampleTwo: null,
        exampleThree: null,

        //新增字段
        studentName: null,
        idNumber: null,
        phonenumber: null,
        unitName: null,
        invoiceCreditCode: null,
        enrollmentSource: null,
        contact: null,
        unitPhonenumber: null,
        trainingType: null,
        projectName: null,
        class: null,
        trainingCategory: null,
        trainingFee: null,
        refund: null,
        enrollmentTime: null,
        remark: null,
        invoiceStatus: null,
        invoiceType: null,
        invoiceCategory: null,
        voucherUploadTime: null,
        paymentTime: null,

        test: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      //数据表格数据项
      //传给备注弹窗的id
      this.remarkTempId =
        selection.length === 1 ? selection[0].registrationId : null;
      this.test = selection[0];
      this.ids = selection.map((item) => item.paymentRecordId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加缴费记录";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const paymentRecordId = row.paymentRecordId || this.ids;
      getRecord(paymentRecordId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改缴费记录";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.paymentRecordId != null) {
            updateRecord(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRecord(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const paymentRecordIds = row.paymentRecordId || this.ids;
      this.$modal
        .confirm(
          '是否确认删除缴费记录编号为"' + paymentRecordIds + '"的数据项？'
        )
        .then(function () {
          return delRecord(paymentRecordIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "training/record/export",
        {
          ...this.queryParams,
        },
        `record_${new Date().getTime()}.xlsx`
      );
    },

    // 新增方法
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.projectId = data.id;
      this.queryParams.pageNum = 1;
      this.getList(this.queryParams);
    },
    // 树节点过滤方法
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    // 获取树形数据
    getProjectTree(val) {
      var params = { projectName: val };
      params.projectId = this.queryParams.projectId;
      projectTreeSelect(params).then((response) => {
        this.projectOptions = response.data;
        this.enabledProjectOptions = this.filterDisabledDept(
          JSON.parse(JSON.stringify(response.data))
        );
      });
    },

    toggleSearch() {
      this.showSearch = !this.showSearch;
    },
    refreshTable() {
      this.getList();
    },
    toggleSort() {
      // 实现排序列切换逻辑
    },
    handleRemark() {
      // 实现缴费备注逻辑
      if (!this.remarkTempId) {
        this.$message.warning("请先选择一条记录");
        return;
      }
      var remarkQuery = {
        foreignId: this.remarkTempId,
        remarkType: "1",
      };

      getRemarksByParams(remarkQuery).then((response) => {
        this.defaultRemark = response.data.remarks || "";
      });

      this.currentPaymentId = this.remarkTempId;
      this.showRemark = true;
    },
    handleRemarkSubmit(data) {
      // 处理备注提交逻辑
      addRemarks(data)
        .then(() => {
          this.$message.success("备注保存成功");
          this.showRemark = false;
          this.getList(); // 刷新列表
        })
        .catch((error) => {
          this.$message.error("备注保存失败: " + error.message);
        });
    },
    handleViewDetail(row) {
      // 实现查看缴费明细逻辑
      const selectedId = this.ids[0] || row.paymentRecordId;

      getPayInfo(selectedId)
        .then((response) => {
          this.formDataCheck = response.data;
          this.showDialogCheck = true;
        })
        .catch((error) => {
          this.$message.error("获取缴费明细失败: " + error.message);
        });
    },
    handleEditDetail() {
      // 实现修改缴费明细逻辑
      const selectedId = this.ids[0];

      getPayInfo(selectedId)
        .then((response) => {
          this.formData = response.data;
          this.showDialogUpdate = true;
        })
        .catch((error) => {
          this.$message.error("获取缴费明细失败: " + error.message);
        });
    },
    handlePayOnline() {
      // 实现线上缴费逻辑
      this.updatePaymentMethodForSelected(1);
    },
    handleTransferPay() {
      // 实现转帐缴费逻辑
      this.updatePaymentMethodForSelected(2);
    },
    handleCashPay() {
      // 实现现金缴费逻辑
      this.updatePaymentMethodForSelected(3);
    },
    handlePosPay() {
      // 实现POS机缴费逻辑
      this.updatePaymentMethodForSelected(4);
    },
    handlePay(row) {
      //已缴费
      const data = {
        paymentRecordIds: Array.isArray(row.paymentRecordId)
          ? row.paymentRecordId
          : [row.paymentRecordId],
        paymentState: "1",
      };
      changePay(data)
        .then((response) => {
          this.$message.success("缴费方式更新成功");
          this.getList(); // 刷新列表
        })
        .catch((error) => {
          this.$message.error("缴费方式更新失败：" + error.message);
        });
    },
    updatePaymentMethodForSelected(val) {
      // 更新缴费方式
      const data = {
        paymentRecordIds: this.ids,
        paymentMethod: val.toString(),
      };
      changePay(data)
        .then((response) => {
          this.$message.success("缴费方式更新成功");
          this.getList(); // 刷新列表
        })
        .catch((error) => {
          this.$message.error("缴费方式更新失败：" + error.message);
        });
    },
    handleViewTransfer() {
      // 实现查看转账凭证逻辑

      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );
      if (!selectedRow) {
        this.$message.warning("请先选择一条记录");
        return;
      }
      getPayInfo(selectedRow.paymentRecordId).then((response) => {
        console.log("转账凭证信息返回数据:", response.data);

        this.voucherInfo = response.data;
        this.showDialogVoucher = true;
      });

      // this.showDialogVoucher = true;
    },
    handlePendingTransfer() {
      // 实现待转账逻辑
      this.updatePaymentSituationForSelected(3);
    },
    handleTransfered() {
      // 实现已转账逻辑
      this.updatePaymentSituationForSelected(8);
    },
    handleCashTransfered() {
      // 实现已现金缴费逻辑
      this.updatePaymentSituationForSelected(9);
    },
    handlePosTransfered() {
      // 实现已POS缴费逻辑
      this.updatePaymentSituationForSelected(10);
    },
    updatePaymentSituationForSelected(val) {
      // 更新缴费方式
      const data = {
        paymentRecordIds: this.ids,
        paymentState: val.toString(),
      };
      changePay(data)
        .then((response) => {
          this.$message.success("缴费方式更新成功");
          this.getList(); // 刷新列表
        })
        .catch((error) => {
          this.$message.error("缴费方式更新失败：" + error.message);
        });
    },

    handleApplyRefund() {
      // 实现查看退费申请逻辑
      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );
      getRefundInfo(selectedRow.paymentRecordId).then((res) => {
        this.refundApplyInfo = selectedRow;

        this.refundApplyInfo.refundTime = res.data.refundTime;
        this.refundApplyInfo.refundPerson = res.data.refundPerson;
        this.refundApplyInfo.refundAmount = res.data.refundAmount;
        this.refundApplyInfo.refundReason = res.data.refundReason;
        console.log("回显信息:", this.refundApplyInfo);
      });

      this.showRefundDialog = true;
    },
    //同意退费---点击
    handleAgreeRefund() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择一条记录");
        return;
      }

      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );

      if (!selectedRow) {
        this.$message.error("未找到对应记录");
        return;
      }

      this.refundName = selectedRow.studentName; // ✅ 设置申请人姓名
      this.agreeRefundDialogVisible = true; // ✅ 显示“同意退费”弹窗
    },

    //同意退费---提交
    handleAgreeRefundSubmit() {
      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );

      if (!selectedRow) {
        this.$message.error("未找到对应记录");
        return;
      }
      const data = {
        paymentRecordId: selectedRow.paymentRecordId,
        paymentState: "7",
      };
      updateRecord(data)
        .then((response) => {
          this.$message.success("已同意退费申请");
          this.agreeRefundDialogVisible = false;
          this.getList(); // 刷新列表
        })
        .catch((error) => {
          this.$message.error("操作失败：" + error.message);
        });
    },
    // 同意退费---确定
    confirmAgreeRefund() {
      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );

      if (!selectedRow) {
        this.$message.error("未找到对应记录");
        return;
      }

      const data = {
        paymentRecordId: selectedRow.paymentRecordId,
        paymentState: "2", // 假设"2"代表"已同意退费"状态，根据实际业务调整
      };

      updateRecord(data)
        .then((response) => {
          this.$message.success("已同意退费申请");
          this.agreeRefundDialogVisible = false;
          this.getList(); // 刷新列表
        })
        .catch((error) => {
          this.$message.error("操作失败：" + error.message);
        });
    },
    handleCancelRefund() {
      // 实现取消退费逻辑
      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );

      getRefundInfo(selectedRow.paymentRecordId).then((res) => {
        this.refundApplyInfoCancel = selectedRow;
        this.refundApplyInfoCancel.refundTime = res.data.refundTime;
        this.refundApplyInfoCancel.refundPerson = res.data.refundPerson;
        this.refundApplyInfoCancel.refundAmount = res.data.refundAmount;
        this.refundApplyInfoCancel.refundReason = res.data.refundReason;

        console.log("回显信息:", this.refundApplyInfoCancel);
      });

      this.showRefundDialogCancel = true;
    },
    handleStartRefund() {
      // 实现发起退费逻辑
      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );
      if (selectedRow) {
        console.log("退费信息:", selectedRow);
        // getPayInfo(selectedRow.paymentRecordId).then((res) => {
        //   this.refundFormData = res.data;

        //   console.log("回显信息:", this.refundFormData);
        // });
        getRefundInfo(selectedRow.paymentRecordId).then((res) => {
          this.refundFormData = selectedRow;
          this.refundFormData.refundTime = res.data.refundTime;
          this.refundFormData.refundPerson = res.data.refundPerson;

          console.log("回显信息:", this.refundFormData);
        });
      } else {
        this.$message.warning("请选择一条记录进行退费");
        return;
      }

      this.showRefundDialogInitiate = true;
    },
    handleAuditRefund() {
      // 实现审核退费逻辑
      if (this.ids.length === 0) {
        this.$message.warning("请先选择一条或多条记录");
        return;
      }

      const selectedRows = this.recordList.filter((item) =>
        this.ids.includes(item.paymentRecordId)
      );

      if (selectedRows.length === 0) {
        this.$message.error("未找到对应记录");
        return;
      }

      // 获取申请人姓名列表
      this.auditRefundNames = selectedRows.map((row) => row.studentName);

      // 显示弹窗
      this.auditRefundDialogVisible = true;
    },
    //审核退费---确定
    confirmAuditRefund() {
      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );
      const data = {
        // paymentRecordIds: this.ids,
        paymentRecordId: selectedRow.paymentRecordId,
        paymentState: "7",
      };

      //需要补充三方接口进行退费

      // 调用后端API审核通过退费
      updateRecord(data)
        .then((response) => {
          this.$message.success("审核通过成功");
          this.auditRefundDialogVisible = false;
          this.getList(); // 刷新列表
        })
        .catch((error) => {
          this.$message.error("审核失败：" + error.message);
        });
    },
    handleAuditRefundClose() {
      this.auditRefundDialogVisible = false;
    },
    // 开票相关方法
    handleEditInvoiceInfo(row) {
      // 实现编辑开票信息逻辑
      if (row) {
        this.currentSelectedRow = row;
      }
      const selectedRow =
        row ||
        this.recordList.find(
          (item) =>
            item.paymentRecordId === (this.ids[0] || row.paymentRecordId)
        );

      console.log("选中的记录:", selectedRow);

      if (selectedRow) {
        // 设置表单数据
        this.invoiceFormData = {
          invoiceType: selectedRow.invoiceType || "",
          invoiceCategory: selectedRow.invoiceCategory || "",
          invoiceUnitName: selectedRow.invoiceUnitName || "",
          invoiceCreditCode: selectedRow.invoiceCreditCode || "",
        };
        // 显示对话框
        this.showEditInvoiceInfo = true;
      } else {
        // 如果没有选中任何记录，初始化为空数据
        this.invoiceFormData = {
          invoiceUnitName: "",
          invoiceCreditCode: "",
          invoiceType: "1",
          invoiceCategory: "1",
        };
        this.showEditInvoiceInfo = true;
      }
    },
    handleIssueInvoice(row) {
      // 实现开发票逻辑
      // 如果是单个记录，count为1
      if (row) {
        this.selectedCount = 1;
      } else {
        // 如果是多选，获取选中的数量
        this.selectedCount = this.ids.length;
      }

      // 显示对话框
      this.showIssueInvoice = true;
    },
    handleMergeInvoice() {
      // 实现合并开票逻辑
      // 获取选中的记录数量
      const selectedCount = this.ids.length;

      if (selectedCount === 0) {
        this.$message.warning("请先选择要合并开票的记录");
        return;
      }

      // 如果只选择了一条记录，可以自动填充信息
      if (selectedCount === 1) {
        const selectedRow = this.recordList.find(
          (item) => item.paymentRecordId === this.ids[0]
        );

        if (selectedRow) {
          this.mergeInvoiceFormData = {
            unitName: selectedRow.unitName || "",
            invoiceCreditCode: selectedRow.invoiceCreditCode || "",
            invoicePhone: selectedRow.phonenumber || "",
          };
        }
      } else {
        // 多条记录时，初始化为空
        this.mergeInvoiceFormData = {
          unitName: "",
          invoiceCreditCode: "",
          invoicePhone: "",
        };
      }

      // 显示对话框
      this.showMergeInvoice = true;
    },
    handleViewInvoice() {
      // 实现查看发票逻辑
    },
    // 同意退换票---点击
    handleAgreeExchange() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择一条记录");
        return;
      }

      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );
      if (!selectedRow) {
        this.$message.error("未找到对应记录");
        return;
      }

      // 设置申请人姓名
      this.exchangeRefundName = selectedRow.studentName;
      this.agreeExchangeDialogVisible = true;
    },
    //同意退换票
    confirmAgreeRefund() {
      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );
      updateInvoice({
        invoiceId: selectedRow.invoiceId,
        registrationId: selectedRow.registrationId,
        invoiceStatus: "4",
      }).then(() => {
        // 模拟成功
        this.$message.success("退费申请已同意");
        // 关闭对话框
        this.agreeExchangeDialogVisible = false;
        // 刷新列表
        this.getList();
      });
    },
    handleStartExchange() {
      // 实现发起退换票逻辑
      if (this.ids.length === 0) {
        this.$message.warning("请先选择一条记录");
        return;
      }

      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );

      if (!selectedRow) {
        this.$message.error("未找到对应记录");
        return;
      }

      var params = {
        invoiceId: selectedRow.invoiceId,
        registrationId: selectedRow.registrationId,
      };
      getInvoiceRefundInfo(params).then((res) => {
        console.log("返回信息:", res);
        const info = res.data;
        // 设置表单数据
        this.startExchangeFormData = {
          ...selectedRow,
          invoiceType: selectedRow.invoiceType,
          invoiceCategory: selectedRow.invoiceCategory,
          invoiceAmount: info.invoiceAmount,
          invoiceNumber: selectedRow.invoiceNumber,
        };

        this.showStartExchangeDialog = true;
      });
    },
    handleStartExchangeClose() {
      this.showStartExchangeDialog = false;
    },
    handleCancelExchange() {
      // 实现取消退换票逻辑
      if (this.ids.length === 0) {
        this.$message.warning("请先选择一条记录");
        return;
      }

      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );

      if (!selectedRow) {
        this.$message.error("未找到对应记录");
        return;
      }

      var params = {
        invoiceId: selectedRow.invoiceId,
        registrationId: selectedRow.registrationId,
      };
      getInvoiceRefundInfo(params)
        .then((res) => {
          if (res.code === 200) {
            this.cancelExchangeFormData = res.data;
            this.showCancelExchangeDialog = true;
          } else {
            this.$message.error(res.msg || "获取退换票信息失败");
          }
        })
        .catch((error) => {
          this.$message.error("获取退换票信息失败: " + error.message);
        });

      // // 设置表单数据
      // this.cancelExchangeFormData = {
      //   ...selectedRow,
      //   invoiceType: selectedRow.invoiceType || "普票/专票",
      //   invoiceCategory: selectedRow.invoiceCategory || "企业/个人",
      //   invoiceAmount: selectedRow.invoiceAmount || "XXX",
      //   invoiceNumber: selectedRow.invoiceNumber || "123456789123456789",
      //   reason: selectedRow.reason || "无",
      // };

      // this.showCancelExchangeDialog = true;
    },
    //修改缴费明细  提交
    handleFormConfirm(data) {
      updateRecord(data.form).then((res) => {
        this.showDialogUpdate = false;
        this.showDialogCheck = false;
        this.$message.success("修改成功");
        this.getList();
      });
    },
    handleFormCancel() {
      console.log("表单已取消");
      this.showDialogUpdate = false;
      this.showDialogCheck = false;
    },

    // 编辑开票信息按钮   提交事件
    handleInvoiceSubmit(formData) {
      const selectedRow =
        this.currentSelectedRow ||
        this.recordList.find((item) => item.paymentRecordId === this.ids[0]);

      // 检查是否存在选中记录和invoiceId
      if (!selectedRow || !selectedRow.invoiceId) {
        this.$message.error("未找到有效的发票信息");
        return;
      }

      // 构造提交数据
      const data = {
        invoiceId: selectedRow.invoiceId,
        ...formData,
      };

      // 调用更新接口
      updateInvoice(data)
        .then((res) => {
          this.showEditInvoiceInfo = false;
          this.$message.success("修改成功");
          this.getList(); // 刷新列表
        })
        .catch((error) => {
          this.$message.error("修改失败: " + error.message);
        });
    },

    // 编辑开票信息关闭处理
    handleEditInvoiceClose() {
      this.showEditInvoiceInfo = false;
    },
    // 开发票关闭处理
    handleIssueInvoiceClose() {
      this.showIssueInvoice = false;
    },

    // 合并开票关闭处理
    handleMergeInvoiceClose() {
      this.showMergeInvoice = false;
    },

    // 处理确认事件
    handleInvoiceConfirm(count) {
      // 这里可以添加开发票的逻辑
      console.log(`准备对${count}条记录开发票`);
      this.$message.success("发票已生成");
      this.showIssueInvoice = false;
      this.getList(); // 刷新列表
    },

    // 处理关闭事件
    handleInvoiceClose() {
      this.showIssueInvoice = false;
    },

    // 处理提交事件
    handleMergeInvoiceSubmit(formData) {
      // 这里可以添加合并开票的逻辑
      console.log("合并开票数据:", formData);
      this.$message.success("合并开票成功");
      this.showMergeInvoice = false;
      this.getList(); // 刷新列表
    },

    // 处理关闭事件
    handleMergeInvoiceClose() {
      this.showMergeInvoice = false;
    },
    // 申请退换票按钮
    handleApplyExchange(row) {
      // 检查是否有选中的记录
      let selectedRow = row;
      if (!selectedRow && this.ids.length > 0) {
        // 如果没有传入row参数，从列表中查找选中的记录
        selectedRow = this.recordList.find(
          (item) => item.paymentRecordId === this.ids[0]
        );
      }

      // 如果仍然没有选中记录，提示用户
      if (!selectedRow) {
        this.$message.warning("请先选择一条记录");
        return;
      }

      // 检查是否有发票ID
      if (!selectedRow.invoiceId) {
        this.$message.warning("该记录没有可退换的发票");
        return;
      }

      // 获取退换票信息
      const params = {
        invoiceId: selectedRow.invoiceId,
        registrationId: selectedRow.registrationId,
      };

      getInvoiceRefundInfo(params)
        .then((res) => {
          if (res.code === 200) {
            this.applyExchangeFormData = res.data;
            // 显示退换票申请对话框
            this.showExchangeDialog = true;
          } else {
            this.$message.error(res.msg || "获取退换票信息失败");
          }
        })
        .catch((error) => {
          this.$message.error("获取退换票信息失败: " + error.message);
        });
    },
    // // 处理退换票申请提交
    // handleExchangeSubmit(data) {
    //   // 这里处理退换票申请的提交逻辑
    //   console.log("退换票申请提交数据:", data);
    //   console.log(
    //     "id:",
    //     this.applyExchangeFormData.invoiceId ||
    //       this.startExchangeFormData.invoiceId
    //   );

    //   const invoiceId =
    //     this.applyExchangeFormData.invoiceId ||
    //     this.startExchangeFormData.invoiceId;
    //   var params = {
    //     invoiceId: invoiceId,
    //     ...data,
    //   };
    //   updateInvoice(params)
    //     .then((response) => {
    //       this.$message.success("退换票申请提交成功");
    //       // 根据数据来源关闭对应的对话框
    //       if (
    //         this.applyExchangeFormData &&
    //         this.applyExchangeFormData.invoiceId
    //       ) {
    //         this.showExchangeDialog = false; // 关闭申请退换票对话框
    //       } else if (
    //         this.startExchangeFormData &&
    //         this.startExchangeFormData.invoiceId
    //       ) {
    //         this.showStartExchangeDialog = false; // 关闭发起退换票对话框
    //       }
    //       this.getList(); // 刷新列表
    //     })
    //     .catch((error) => {
    //       this.$message.error("退换票申请提交失败: " + error.message);
    //     });
    // },
    // 处理退换票申请提交
    handleExchangeSubmit(data) {
      // 这里处理退换票申请的提交逻辑
      console.log("退换票申请提交数据:", data);

      const invoiceId =
        this.applyExchangeFormData?.invoiceId ||
        this.startExchangeFormData?.invoiceId;

      if (!invoiceId) {
        this.$message.error("发票信息不完整");
        return;
      }

      var params = {
        invoiceId: invoiceId,
        ...data,
      };

      updateInvoice(params)
        .then((response) => {
          this.$message.success("退换票申请提交成功");

          // 确保关闭正确的对话框
          if (this.showExchangeDialog) {
            this.showExchangeDialog = false;
          }
          if (this.showStartExchangeDialog) {
            this.showStartExchangeDialog = false;
          }

          this.getList(); // 刷新列表
        })
        .catch((error) => {
          this.$message.error("退换票申请提交失败: " + error.message);
        });
    },
    // 处理退换票申请对话框关闭
    handleExchangeClose() {
      this.showExchangeDialog = false;
    },
    handleCancelExchangeClose() {
      this.showCancelExchangeDialog = false;
    },
    handleRemarkClose() {
      this.showRemark = false;
    },
    // 退费申请--提交按钮
    handleRefundSubmit(submitData) {
      // 处理提交后关闭对话框
      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );
      console.log("参数:", submitData);
      var params = {
        paymentRecordId: selectedRow.paymentRecordId,
        paymentState: submitData.auditResult.paymentState,
      };
      console.log("参数:", params);
      if (selectedRow) {
        updateRecord(params).then((res) => {
          this.showRefundDialog = false;
          this.getList(); // 刷新列表
        });
      } else {
        this.$message.error("请先选择一条记录");
        return;
      }

      // this.showRefundDialog = false;
    },
    handleCheckRefundClose() {
      this.showRefundDialog = false;
    },
    //发起退费按钮
    handleRefundSubmitInitiate(submitData) {
      // 处理提交后关闭对话框
      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );
      var params = {
        paymentRecordId: selectedRow.paymentRecordId,
        refundAmount: submitData.auditForm.refundAmount,
        refundReason: submitData.auditForm.refundReason,
        paymentState: "6",
      };
      console.log("参数:", params);
      if (selectedRow) {
        updateRecord(params).then((res) => {
          this.showRefundDialogInitiate = false;
          this.getList(); // 刷新列表
        });
      } else {
        this.$message.warning("请选择一条记录进行退费");
        return;
      }
    },
    handleInitiateRefundClose() {
      this.showRefundDialogInitiate = false;
    },

    // 取消退费申请---提交
    handleRefundSubmitCancel() {
      // 处理提交后关闭对话框
      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );
      var params = {
        paymentRecordId: selectedRow.paymentRecordId,
        paymentState: "1",
      };
      if (selectedRow) {
        updateRecord(params).then(() => {
          this.showRefundDialogCancel = false;
          this.getList(); // 刷新列表
        });
      } else {
        this.$message.warning("请选择一条记录进行退费");
        return;
      }
    },
    //转账确认按钮
    handleConfirmTransferred() {
      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );
      //修改缴费状态 2
      var params = {
        paymentRecordId: selectedRow.paymentRecordId,
        paymentState: "2",
      };
      updateRecord(params).then(() => {
        this.$message.success("转账成功");
        this.showDialogTransferred = false;
        this.getList(); // 刷新列表
      });
      // this.showDialogVoucher = false;
      // this.getList(); // 刷新列表
    },
    handleVoucherDialogClose() {
      this.showDialogVoucher = false;
    },
    handleCancelExchangeSubmit(data) {
      // 处理取消退换票提交逻辑
      console.log("取消退换票提交数据:", data);

      var params = {
        invoiceId: this.cancelExchangeFormData.invoiceId,
        invoiceStatus: "1",
      };
      updateInvoice(params).then(() => {
        this.$message.success("取消退换票成功");
        this.showCancelExchangeDialog = false;
        this.getList(); // 刷新列表
      });
    },
    // 打开取消同意退费弹窗
    handleCancelAgreeRefund() {
      if (this.ids.length === 0) {
        this.$message.warning("请先选择一条记录");
        return;
      }

      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );

      if (!selectedRow) {
        this.$message.error("未找到对应记录");
        return;
      }

      this.refundName = selectedRow.studentName; // 设置申请人姓名
      this.cancelAgreeRefundDialogVisible = true; // 显示弹窗
    },

    // 确认取消同意退费
    confirmCancelAgreeRefund() {
      const selectedRow = this.recordList.find(
        (item) => item.paymentRecordId === this.ids[0]
      );
      const data = {
        paymentRecordId: selectedRow.paymentRecordId,
        paymentState: "1",
      };
      updateRecord(data)
        .then(() => {
          this.$message.success("已取消同意退费申请");
          this.cancelAgreeRefundDialogVisible = false;
          this.getList(); // 刷新列表
        })
        .catch((error) => {
          this.$message.error("取消失败：" + error.message);
        });
    },
  },
  watch: {
    // 根据名称筛选部门树
    projectName(val) {
      this.$refs.tree.filter(val);
      this.getProjectTree(val);
    },
  },
};
</script>
<style scoped>
.app-container {
  display: flex;
}
.el-col {
  height: 100%;
}
.custom-tree-node {
  display: flex;
  align-items: center;
  gap: 4px;
}
/* 按钮组容器样式 */
.button-groups-container {
  margin-bottom: 20px;
}

/* 每行按钮组的间距 */
.button-group-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding: 8px 0;
  border-bottom: 1px solid #ebeef5;
}

/* 最后一行不显示底部边框 */
.button-group-row:last-child {
  margin-bottom: 0;
  border-bottom: none;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

/* 按钮样式调整 */
.button-group .el-button {
  min-width: 80px;
  padding: 6px 12px;
}

/* 弹窗按钮样式 */
.agree-refund-dialog .el-button--primary {
  background-color: #007bff;
  border-color: #007bff;
  color: white;
}

.agree-refund-dialog .el-button--default {
  background-color: transparent;
  border-color: #dcdfe6;
  color: #606266;
}

/* 刷新按钮组样式 */
.button-group-right {
  float: right;
  margin-right: 50px;
}
</style>
